package com.hanxiaozhang.advanced.no1confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

/**
 * 〈一句话功能简述〉<br>
 * 〈Confirm机制〉
 * 消息成功进入Queue，队列就会给生产者进行反馈
 *
 * @author hanxinghua
 * @create 2022/9/24
 * @since 1.0.0
 */
public class Producer {

    private static final String QUEUE_NAME = "confirm-01";

    public static void main(String[] args) throws Exception {
        // 创建链接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置RabbitMQ所在主机ip或者主机名
        factory.setHost("localhost");
        // 创建一个连接
        Connection connection = factory.newConnection();
        // 创建一个频道
        Channel channel = connection.createChannel();
        // 开启confirm消息确认机制
        channel.confirmSelect();
        // 添加确认监听
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("发送成功的监听.....");
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("发送失败的监听.....");
            }
        });
        String message = "hello world!";
        channel.queueDeclare(QUEUE_NAME, false, false, true, null);
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println("Sent '" + message + "'");

    }

}
